'use strict';
(function() {

    function getFileType(url) {
        var match = url.match(/\.(\w+)$/);
        if (match) {
            return match[1];
        } else {
            return ''
        }
    }

    function getFileName(url) {
        var match = url.match(/\/([.\w-]+)$/);
        if (match) {
            return match[1];
        } else {
            return ''
        }
    }

    function firstUper(str) {
        str = str.toLowerCase();
        return str.replace(/\b(\w)|\s(\w)/g, function(m) {
            return m.toUpperCase();
        });
    }

    function loadResources(scope, $templateCache, $http, toState) {
        var fileInfos = toState.fileInfos || [];

        // 初始化，以免有残留。
        var index = 0;
        scope.activeFile = 1;
        var mainHtml = {
            id: ++index,
            type: 'html',
            name: 'HTML',
            description: '主模板的HTML文件',
            url: toState.templateUrl.replace(scope.APP_BASE_PATH, ""),
            source: $templateCache.get(toState.templateUrl)[1]
        };
        var mainJs = {
            id: ++index,
            type: 'js',
            name: 'JS',
            description: '主控制器的JS文件',
            url: '',
            source: ''
        };
        // var mainCss = {
        //     id: ++index,
        //     type: 'css',
        //     name: 'CSS',
        //     description: '主模板的CSS文件',
        //     url: '',
        //     source: ''
        // };

        //以默认规则加载文件
        var modulename = getFileName(toState.templateUrl).replace(".html", "");
        var baseDir = toState.templateUrl.substring(0, toState.templateUrl.lastIndexOf("/view/"));

        scope.basePath = baseDir.startsWith("/") ? baseDir : "app/" + baseDir;

        // mainCss.url = baseDir + "/css/" + modulename + ".css";
        // $http.get(mainCss.url).success(function(data) {
        //     mainCss.source = data;
        // });

        mainJs.url = baseDir.replace(scope.APP_BASE_PATH, "") + "/js/controller/" + firstUper(modulename) + 'Controller.js';
        $http.get(mainJs.url).success(function(data) {
            mainJs.source = data;
        });



        scope.fileGroups = [];
        scope.fileGroups.push([
            mainHtml,
            mainJs
            // mainCss
        ]);

        //加载其它资源文件
        angular.forEach(toState.fileInfos, function(group, key) {
            var fileGroup = [];
            if (key == 0) {
                fileGroup = scope.fileGroups[0];
            } else {
                scope.fileGroups.push(fileGroup);
            }
            angular.forEach(group, function(fileInfo, key) {
                //过滤已加载文件
                if (mainHtml.url == fileInfo.url || mainJs.url == fileInfo.url) {
                    return false;
                }
                $http.get(scope.APP_BASE_PATH + fileInfo.url).success(function(data) {
                    fileGroup.push({
                        id: ++index,
                        type: getFileType(fileInfo.url),
                        name: getFileName(fileInfo.url),
                        description: fileInfo.description,
                        url: fileInfo.url,
                        source: typeof(data) == "string" ? data : JSON.stringify(data)
                    });
                }).error(function(data, status, headers, config) {
                    console.info("error.....");
                    console.info(data);
                });
            });
        });
    }

    /**
     * 支持查看源代码的指令，此版本只能配合ui-router使用
     * 原理：
     * 拦截路由变化的事件，并且根据route中的template或templateUrl参数获得view的源代码。
     * 根据控制器名称和相应的规约获得动态取得controller的源代码。
     */
    ngApp.directive('showcaseSource', ['$rootScope', '$state', '$templateCache', '$http', 'HlCssTypesConstant', 'AppConfigConstant', function($rootScope, $state, $templateCache, $http, HlCssTypesConstant, AppConfigConstant) {
        var appBasePath = AppConfigConstant.APP_BASE_PATH;

        return {
            restrict: 'EA',
            scope: {},
            templateUrl: appBasePath + 'showcase/directive/showcase-source/view/showcase-source.html',
            link: function(scope, element, attrs) {
                scope.APP_BASE_PATH = AppConfigConstant.APP_BASE_PATH;

                scope.hlcsstype = "default";

                scope.hlcsstypes = HlCssTypesConstant;

                scope.isActive = function(file) {
                    return file.id === scope.activeFile;
                };
                scope.setActive = function(file) {
                    scope.activeFile = file.id;
                };

                $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
                    loadResources(scope, $templateCache, $http, toState);
                });

                loadResources(scope, $templateCache, $http, $state.current);
            }
        }
    }]);

})();
